/**
 * Created by zhangbo on 27/01/14.
 */

var CesiumSelect = (function () {

    function _(cesiumViewer, opt) {
        var option = this._option = opt || {infowindow:{offset:{x:0, y:-10}}};
        var viewer = this._viewer = cesiumViewer;
        var infoWindow = this._infoWindow = new InfoWindow(viewer, this._option.infowindow);
        var selectedObject = this._selectedObject = null;
        var handler = this._handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        // this._infoWindow.showAt(Cesium.Matrix4.multiplyByPoint(modelMatrix, boundingSphere.center, new Cesium.Cartesian3()), primitiveId, primitiveId);
        // this._infoWindow.bindTarget(pickedObject);
        // this._infoWindow.setVisible(true);
        viewer.scene.primitives.add(this._infoWindow);
        infoWindow.closeHandler = function(){
        	if(Cesium.defined(self._selectedObject)){
            	var selectedPrimitiveId = self._selectedObject.primitive.id ? self._selectedObject.primitive.id : '';
            	if(typeof selectedPrimitiveId === 'string'){
            		self._selectedObject.primitive.silhouetteSize = 0;
            	}
            	else if(typeof selectedPrimitiveId === 'object'){
            		self._selectedObject.id.model.silhouetteSize = 0;
            	}
            }
        	self._selectedObject = null;
        	self._infoWindow.bindTarget(null);
        	self._infoWindow.setContent('');
        	viewer.selectedEntity = null;
        	viewer.trackedEntity = null;
        	viewer.entities.removeById('cesium_select');
        }
        var self = this;
        handler.setInputAction(function (click) {
            var pickedObject = viewer.scene.pick(click.position);
            console.log(pickedObject)
            if (Cesium.defined(pickedObject)) {
                if(Cesium.defined(self._selectedObject)){
                	var selectedPrimitiveId = self._selectedObject.primitive.id ? self._selectedObject.primitive.id : '';
                	if(typeof selectedPrimitiveId === 'string'){
                		self._selectedObject.primitive.silhouetteSize = 0;
                	}
                	else if(typeof selectedPrimitiveId === 'object'){
                		self._selectedObject.id.model.silhouetteSize = 0;
                	}
                	
                	self._infoWindow.bindTarget(null);
                	self._infoWindow.setContent('');
                	self._infoWindow.setVisible(false);
                }
            	viewer.selectedEntity = null;
            	viewer.trackedEntity = null;
            	viewer.entities.removeById('cesium_select');
                	
                self._selectedObject = pickedObject;
                var objectId = pickedObject.primitive.id ? pickedObject.primitive.id : undefined;
                if(typeof objectId === 'string'){//primitive model
                    self._selectedObject.primitive.silhouetteSize = 2.0;
                    self._infoWindow.setTitle(objectId);
                    var isBinding = self._selectedObject.primitive['attributesBinding'];
                    var attributes = self._selectedObject.primitive['attributes'];
                    var name = self._selectedObject.primitive['name'];
                    self._infoWindow.setTitle(name);
                    if(isBinding){
                    	self._infoWindow.bindTarget(self._selectedObject);
                    	self._infoWindow.setContent(attributes);
                    	self._infoWindow.setVisible(true);
                    }
                    else{
                    	var boundingSphere = self._selectedObject.primitive.boundingSphere;
                        var modelMatrix = self._selectedObject.primitive.modelMatrix;
                    	if(Cesium.defined(boundingSphere)  && Cesium.defined(modelMatrix)){
                    		var position = Cesium.Matrix4.multiplyByPoint(modelMatrix, boundingSphere.center, new Cesium.Cartesian3());
                    		self._infoWindow.showAt(position, objectId, attributes);
                    	}
                    }
                }
                else if(typeof objectId === 'object'){//entity model
                	self._selectedObject.id.model.silhouetteColor = Cesium.Color.RED;
                	self._selectedObject.id.model.silhouetteSize = 2.0;
                	var isBinding = self._selectedObject.id['attributesBinding'];
                	var attributes = self._selectedObject.id['attributes'];
                	var name = self._selectedObject.id['name'];
                	self._infoWindow.setTitle(name);
                	if(isBinding){
                    	self._infoWindow.bindTarget(self._selectedObject);
                    	self._infoWindow.setContent(attributes);
                    	self._infoWindow.setVisible(true);
                    }
                    else{
                    	var boundingSphere = self._selectedObject.primitive.boundingSphere;
                        var modelMatrix = self._selectedObject.primitive.modelMatrix;
                    	if(Cesium.defined(boundingSphere)  && Cesium.defined(modelMatrix)){
                    		var position = Cesium.Matrix4.multiplyByPoint(modelMatrix, boundingSphere.center, new Cesium.Cartesian3());
                    		self._infoWindow.showAt(position, name, attributes);
                    	}
                    };
                }
                else if(typeof pickedObject.id === 'object'){//entity geometry
                	var objectId = pickedObject.id;
                	var name = objectId['name'];
                	var attributes = objectId['attributes'];
//                	self._selectedObject.primitive.silhouetteColor = Cesium.Color.RED;
//                	self._selectedObject.primitive.silhouetteSize = 2.0;
                	self._infoWindow.setTitle(name);
                	if(Cesium.defined(objectId.polylineVolume)){
                		var position = viewer.scene.pickPosition(click.position);
                		self._infoWindow.showAt(position, name, attributes);
                		
                		var radius = objectId['radius'] || 5;
                		var thisPolylineVolume = objectId.polylineVolume;
                		var thisPVPositions = thisPolylineVolume.positions._value;
                		var hlPositions = [];
                		for(var i = 0; i < thisPVPositions.length; i++){
                			hlPositions.push(new Cesium.Cartesian3(thisPVPositions[i].x, thisPVPositions[i].y, thisPVPositions[i].z - 1));
                		}
                		function computeCircle(radius) {
                            var positions = [];
                            for (var i = 0; i < 360; i++) {
                                var radians = Cesium.Math.toRadians(i);
                                positions.push(new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
                            }
                            return positions;
                        }
                		viewer.entities.add({
                			id: 'cesium_select',
                            polylineVolume: {
                                positions: hlPositions,
                                shape: computeCircle(radius + 1),
                                material: Cesium.Color.RED.withAlpha(0.3),
                            },
                		});
                	}
                	else if(Cesium.defined(objectId.ellipsoid)){
                		var position = new Cesium.Cartesian3(objectId.position._value.x, objectId.position._value.y, objectId.position._value.z);
                		self._infoWindow.showAt(position, name, attributes);
                		
                		var thisEllipsoid = objectId.ellipsoid;
                		viewer.entities.add({
                			id: 'cesium_select',
                			position: position,
                			ellipsoid: {
                                material: Cesium.Color.RED.withAlpha(0.3),
                                radii: new Cesium.Cartesian3(thisEllipsoid.radii._value.x + 1, thisEllipsoid.radii._value.y + 1, thisEllipsoid.radii._value.z + 1),
                            },
                		});
                	}
                	else if(Cesium.defined(objectId.billboard)){
                		var position = new Cesium.Cartesian3(objectId.position._value.x, objectId.position._value.y, objectId.position._value.z);
                		self._infoWindow.showAt(position, name, attributes);
                		
                		var thisEllipsoid = objectId.ellipsoid;
                	}
                }
                else{
                	self._infoWindow.bindTarget(null);
                	self._infoWindow.setContent('');
                	self._infoWindow.setVisible(false);
                }
            }
//            else {
//            	self._selectedObject = null;
//            	self._infoWindow.bindTarget(null);
//            	self._infoWindow.setContent('');
//            	self._infoWindow.setVisible(false);
//            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    };

    _.prototype.destroy = function () {
        this._viewer.scene.primitives.add(this._infoWindow);
        this._handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        this._handler.destroy();
        this._handler = null;
    };

    return _;
})();
